<template>
  <van-uploader
    v-bind="$attrs"
    v-on="$listeners"
    class="upload-demo"
    action="/"
    multiple
    v-model="fileAll"
    @delete="removeFile"
    :before-read="breforeUpload"
    :after-read="uploadFile"
    :on-preview="getFile"
    :disabled="disabled"
    :deletable="!disabled"
    :max-count="disabled ? (fileAll.length == 0 ? 1 : fileAll.length) : 30"
    list-type="picture"
    ref="elupload"
  />
</template>

<script>
import { uploadFileUploadFile as uploadApi } from "@/api";
import {
  fileTypeValidate,
  acceptValue,
  isImg
} from "@/utils/fileTypeValidation";
import baseUrl from "@/api/request/url";
import { is } from "@babel/types";
export default {
  name: "FormFileList",
  props: {
    value: {
      type: Array,
      default: []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      acceptValue,
      isImg,
      msg: "",
      loading: false,
      failed: false,
      fileAll: []
    };
  },
  mounted() {
    this.fileAll = this.fileList;
  },
  computed: {
    fileList() {
      return this.files.map(item => {
        return {
          url: baseUrl + item
        };
      });
    },
    files: {
      get() {
        return this.value.map(item => {
          return item;
        });
      },
      set(e) {
        this.$emit("input", e);
      }
    },
    tips() {
      if (!this.value) {
        return true;
      }
      return false;
    }
  },
  methods: {
    showTips(e) {
      e.preventDefault();
      //
    },
    getFile(e) {
      let otherWindow = window.open();
      otherWindow.opener = null;
      window.open(e.url);
    },
    async uploadFile(e) {
      // value 值会默认赋值，防止
      this.$emit("input", this.files);
      const type = fileTypeValidate(e.file.name);
      this.loading = true;
      const formData = new FormData();
      formData.append("files", e.file);
      //   formData.append("type", type);

      try {
        let res = await uploadApi(formData);
        this.files.push(res.data[0]);
        this.$emit("input", this.files);
      } catch (error) {
        this.$refs.elupload.tempIndex -= 1;
      }
      //   this.files = [...this.files];
      this.loading = false;
    },
    breforeUpload(file) {
      const type = isImg(file.name);
      if (!type || (this.type && type !== this.type)) {
        this.failed = true;
        this.$notified.error({
          message: "上传失败，不支持的文件类型"
        });
      }
      return Boolean(type);
    },
    beforeRemove(file, fileList) {
      if (this.failed) {
        this.failed = false;
        return;
      }
      return this.$Dialog(`确定移除 ？`);
    },
    removeFile(e, detail) {
      this.files = this.files.filter((i, index) => {
        return detail.index != index;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.buttonDisabled {
  &::v-deep {
    & > div {
      display: none;
    }
  }
}
</style>
